package com.adnaan.api.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.adnaan.api.mapper.AppUserMapper;
import com.adnaan.api.model.entity.AppUser;
import com.adnaan.api.service.AppUserService;
import com.adnaan.common.exception.BusinessException;
import com.adnaan.common.model.dto.auth.LoginRequest;
import com.adnaan.common.model.dto.auth.LoginResponse;
import com.adnaan.common.model.dto.auth.RegisterRequest;
import com.adnaan.common.utils.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.HashSet;

/**
 * 前台用户服务实现类
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {

    /**
     * 用户注册
     *
     * @param registerRequest 注册请求
     * @return 用户ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long register(RegisterRequest registerRequest) {
        // 校验用户名是否已存在
        if (isUsernameExists(registerRequest.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        // 校验密码和确认密码是否一致
        if (!registerRequest.getPassword().equals(registerRequest.getConfirmPassword())) {
            throw new BusinessException("两次输入的密码不一致");
        }

        // 创建用户
        AppUser user = new AppUser();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(PasswordUtil.encode(registerRequest.getPassword()));
        user.setNickname(StringUtils.hasText(registerRequest.getNickname()) ?
                registerRequest.getNickname() : registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setMobile(registerRequest.getMobile());
        user.setStatus(0); // 正常状态

        // 保存用户
        save(user);

        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param loginRequest 登录请求
     * @return 登录响应
     */
    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 查询用户
        AppUser user = getByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new BusinessException("用户名或密码错误");
        }

        // 校验密码
        if (!PasswordUtil.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        // 校验用户状态
        if (user.getStatus() != 0) {
            throw new BusinessException("账号已被禁用");
        }

        // 执行登录
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();

        // 返回登录信息
        return LoginResponse.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .token(token)
                .roles(new HashSet<>(Collections.singletonList("user")))
                .permissions(new HashSet<>())
                .build();
    }

    /**
     * 通过用户名查询用户
     *
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public AppUser getByUsername(String username) {
        LambdaQueryWrapper<AppUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUser::getUsername, username);
        return getOne(queryWrapper);
    }

    /**
     * 获取当前登录用户
     *
     * @return 登录响应
     */
    @Override
    public LoginResponse getCurrentUser() {
        // 校验登录状态
        Long userId = StpUtil.getLoginIdAsLong();

        // 查询用户
        AppUser user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 返回用户信息
        return LoginResponse.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .token(StpUtil.getTokenValue())
                .roles(new HashSet<>(Collections.singletonList("user")))
                .permissions(new HashSet<>())
                .build();
    }

    /**
     * 检查用户名是否已存在
     *
     * @param username 用户名
     * @return 是否存在
     */
    private boolean isUsernameExists(String username) {
        LambdaQueryWrapper<AppUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUser::getUsername, username);
        return count(queryWrapper) > 0;
    }
} 